<template>
  <div class="page-container page-footer-btn">
    <van-cell-group>
      <van-field is-link @click="showPopup" placeholder="请选择供应商" label="供应商" :value="out.supplierName"></van-field>
      <FortenScan
        ref="scanDom"
        propPlaceholder="请扫描SN/RFID"
        propErrorMsg="请扫描正确的RFID/SN"
        :propTypeArr="['sn','rfid']"
        @scanCall="handleScanOver"
      />

      <van-field label="仓库:" label-align="left" v-model="out.warehouseName" size="mini" disabled/>
      <van-field v-if="out.id" label="出库单号:" label-align="left" v-model="out.busKey" size="mini" disabled />
      <van-field v-if="out.id" label="出库金额:" label-align="left" v-model="out.amount" size="mini" disabled />
      <van-field v-if="out.id" label="出库数量:" label-align="left" v-model="out.qty" size="mini" disabled />
    </van-cell-group>
    <van-divider><span style="font-size:9px">出库单明细</span></van-divider>
    <div class="items-container">
      <ReturnItem
        style="margin-top:5px;"
        v-for="item in outItems"
        :key="item.id"
        :value="item"
        v-on:delete="deleteItem(item)"
      />
    </div>
      <van-row  class="footer-btn">
        <van-col span="24">
          <flow-buttons
            :propFlowKey="propFlowKey"
            @button-click="handleFlowButtonClick"
          />
        </van-col>
       <!-- <van-col span="6">
          <van-button text="重置"    type="primary" @click="handleCreate" ></van-button>
        </van-col>-->
      </van-row>

     <!-- 选择供应商-->
      <FortenList ref="listItem" :propAutoFetchData = 'false'
                  :propIsRadio="true"
                  :propFlagPopup="true"
                  :propSearchFields="['name','mscmCode']"
                  :propSearchTextAppend="'名字/编码'"
                  propUrl="/base/supplier/page"
                  @change="change"
      >
        <template  #default="{item}"  >
          <van-row >
            <van-col span="4">
              <van-radio   :name="item"  />
            </van-col>
            <van-col span="4">名字：</van-col>
            <van-col span="16">{{item.name}}</van-col>
          </van-row>
          <van-row >
            <van-col span="4">
            </van-col>
            <van-col span="4">代码：</van-col>
            <van-col span="16">{{item.mscmCode}}</van-col>
          </van-row>
        </template>
      </FortenList>
    </div>
</template>

<script>
/* eslint-disable*/
import { Button , Popup, Sticky, List, Image as VanImage, NumberKeyboard, DatetimePicker, Swipe, SwipeItem, RadioGroup, Radio, Checkbox, CheckboxGroup   } from 'vant'
import Vue from 'vue'
import FlowButtons from '@/components/FlowButtons.vue'
import ReturnItem from './ReturnItem.vue'
import barcodeParse from '@/util/barcodeParse.js'

Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(DatetimePicker)
Vue.use(VanImage)
Vue.use(NumberKeyboard)
Vue.use(List)
Vue.use(Popup)

export default {
  data() {
    return {
      out: {},
      outItems: {},
      images: [],
      searchedList: [],
      supplierList: [],
      outItem:[],
      result: [],
      ids: [],
      searchValue: '',
      scan: '',
      show: false,
    }
  },
  props: {
    propFlowKey: String
  },
  mounted() {
    this.$set(this.out, 'supplierName' , '')
    this.$refs.scanDom.focus()
    this.getWarehouse()
    this.getSupplierList()
  },
  computed: {
    cpButtonDisable() {
      return !this.deliver.code
    }
  },
  methods: {
    getWarehouse(){
      this.$set(this.out, 'warehouseId',this.$store.getters.currentWarehouse.id)
      this.$set(this.out, 'warehouseName',this.$store.getters.currentWarehouse.warehouseName)
    },
    handleScanClear(event) {
      this.scan = ''
    },
    showPopup() {
      this.$refs.listItem.show()
    },
    deleteItem(value){
      this.ids.push(value.id)
      const params = { ids: this.ids }
      this.$ajax.delete('/wm/out_order_item/delete', {data: params}).then(resp => {
        this.utils.loadHide()
        if(resp.code == 0){
          this.$notify.success('删除成功')
          this.getOutOrder(this.out.busKey)
        } else {
          this.$notify.warning(resp.msg)
        }
      }).catch(err =>{
        this.utils.loadHide()
      })
    },
    handleScanOver(scanValue) {
      let params = {
        isScan: 1,
        uniqueCode: scanValue
      }
      this.$ajax.get('/wm/stock/getStockByUniqueCode', {params}).then(resp => {
        if(resp.code == 0){
          let item = resp.data
          console.log('item', item)
          if(item.warehouseId != this.out.warehouseId){
            this.$notify.warning('耗材所在仓库与当前仓库不一致！')
            return
          }
          if(this.out.supplierName != '' && item.supplierName != this.out.supplierName){
            this.$notify.warning('耗材所属供应与当前供应商不一致！')
            return
          }
          this.$set(this.out, 'supplierId' , item.supplierId)
          this.$set(this.out, 'supplierName' , item.supplierName)
          this.$set(this.out, 'flagConsignment' , item.flagConsignment)
          this.$set(this.out, 'flagOmoc' , item.flagOmoc)
          this.saveOder(item.sn)
        }
        this.utils.clearFocus(this,'scanDom','scan')
      })
    },
    saveOder(code) {
      this.utils.loadShow()

      if(!this.out.id){
        this.saveOutOrder(code)
      } else {
        this.saveItem(code)
      }

    },
    saveOutOrder(code){
      const currentUser = this.$store.getters.currentUser.currentUser
      const params = {
        busDate: new Date().format('yyyy-MM-dd'),
        busType: 'OUT_SP',
        busUser: currentUser.name,
        flagConsignment: this.out.flagConsignment,
        flagOmoc: this.out.flagOmoc,
        supplierId: this.out.supplierId,
        supplierName: this.out.supplierName,
        warehouseId: this.out.warehouseId,
        warehouseName: this.out.warehouseName
      }
      this.$ajax.post('/wm/out_order/save', params).then(res => {
        if(res.code == 0){
          this.out = res.data
          this.saveItem(code)
        }
      }).catch(err =>{
        this.utils.loadHide()
        return
      })
    },
    saveItem(code){
      const params= {
        workOrderId:this.out.id,
        uniqueCode: code,
        supplierId: this.out.supplierId,
        warehouseId: this.out.warehouseId,
        flagConsignment: this.out.flagConsignment,
        flagOmoc: this.out.flagOmoc,
        isScan: 1
      }
      this.$ajax.post('/wm/out_order_item/scan', params).then(resp => {
        if (resp.code == 0) {
          this.getOutOrder()
        }
      }).catch(err => {
        this.utils.loadHide()
        return
      })
    },
    getOutOrder(){
      const params = {
        code: this.out.busKey
      }
      this.$ajax.get('/wm/out_order/getOutOrder', { params }).then(response => {
        this.utils.loadHide()
        if(response.code ==0){
          this.out = response.data.out || []
          this.outItems = response.data.outItems || []
          this.out.qty = this.outItems.length
        } else {
            this.$notify.error(response.msg)
          return
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    async handleFlowButtonClick(button) {
      if(!this.out.id){
        this.$notify.warning('请先创建出库单')
        return
      }
      const result = await this.$dialog.confirm({
        title: '流程确认',
        message: `确定要进行${button.title}操作吗？`
      });
      if (!result) return;

      this.utils.loadShow()
      let busId = '';
      busId = this.out.id
      const flowKey = this.propFlowKey.split(':')[0];
      let params = {
        flowKey,
        buttonKey: button.code,
        busId: this.out.id
      };
      this.$ajax.post('/wm/out_order/flow_change', params).then(response => {
        this.utils.loadHide()
        if (response.code === 0) {
          this.$notify.success(`${button.title}操作成功！`);
          this.clearForm()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    clearForm() {
      this.out = {};
      this.outItems = [];
      this.scan = '';
      this.$refs.scanDom.focus()
    },
    spfilter() {
        this.searchedList = this.supplierList.filter(item => item.name.indexOf(this.out.supplierName) > -1
            || this.pyutils.chineseToPinYin(item.name).indexOf(this.out.supplierName) > -1)
    },
    getSupplierList(){
      // this.$ajax.get('/base/supplier/list').then(resp => {
      //   this.utils.loadHide()
      //   if (resp.code == 0) {
      //     this.supplierList = resp.data || []
      //     this.searchedList = resp.data || []
      //   }
      // }).catch(err=> {
      //   this.utils.loadHide()
      // })
    },
    spCheck(item, index){
      if (this.out.supplierId == item.id) {
        this.show = false
        return
      }
      this.reCheck(item)
    },
    reCheck(item){
      this.$set(this.out, 'supplierId' , item.id)
      this.$set(this.out, 'supplierName' , item.name)
      this.show = false
      this.utils.clearFocus(this,'scanDom','scan')
    },
    handleCreate(){
      if (this.out.id) {
        this.$dialog.confirm({
          message: '当前单据未提交，是否创建新单据?',
        }).then(() => {
          this.utils.loadShow()
          this.clearForm()
          this.getWarehouse()
          this.getSupplierList()
        }).catch(() => {
          // on cancel
        })
      }
    },
    change(item) {
      if (this.out.supplierId == item.id) {
        return
      }
      this.reCheck(item)
    }
  },
  components: {
    ReturnItem,
    FlowButtons,
    RadioGroup,
    Sticky,
    Checkbox,
    CheckboxGroup,
    Radio,
    Button
  }

}
</script>

<style lang="scss" scoped>
  .items-container {
    min-height: 80px;
  }
  .popup {
    width: 80%;
    height: 100%;
  }
  .footer{
    position: fixed;
    left: 0px;
    bottom: 0px;
    width: 100%;
    height: 50px;
  }
  .btn-container {
    margin-left: 1%;
    margin-right: 1%;
    flex-direction:column ;
    justify-content: space-between;
    display:inline-block;
    width: 80%;
  }
  .creat{
    margin-left: 1%;
    flex-direction:column ;
    justify-content: space-between;
  }
</style>
